<template>
  <div class="main">
    <div class="header">
      <van-sticky>
        <div class="nav">
          <img :src="back" alt="" @click="handleBack"/>
          <div class="title">{{ title }}亲友</div>
          <div class="del" v-if="title=='编辑'" @click="del">删除</div>
          <div class="search" v-if="title=='新增'" @click="gotoScanner"></div>
        </div>
      </van-sticky>
      <div class="tx">
        <!--        @click="changeImg()"-->
        <div class="avatar"
             :style="{backgroundImage: `url(${userInfo.avatar? store.state.imgUrl + userInfo.avatar : logo})`}">
          
        </div>
        <!-- <van-image class="avatar" :src="userInfo.avatar ? store.state.imgUrl + userInfo.avatar : logo"
                   round
        /> -->
      </div>
      <!--      <div class="change-avatar">-->
      <!--        点击更换头像-->
      <!--      </div>-->
      <!--    <div class="body">-->
      <!--      <van-cell title="亲属关系" is-link :value="userInfo.friendLabelTitle" @click="showRelation=true"/>-->
      <van-cell title="亲属关系" is-link :value="userInfo.friendLabel" @click="gotoRelation()"/>
      <van-field
          v-model="userInfo.friendName"
          label="姓名"
          placeholder="请输入姓名"
          input-align="right"
          maxlength="16"
      />
      <van-cell
          title="手机号"
          is-link
          v-if="title=='新增'"
          @click="handlePhone"
          :value="userInfo.friendPhone"
      />
      <van-cell
          title="手机号"
          is-link
          v-if="title=='编辑'"
          :value="userInfo.friendPhone"
      />
      <div class="field-with-switch">
        <van-field label="监护提醒"></van-field>
        <van-switch v-model="defaultValue" size="24"></van-switch>
      </div>
      <van-cell
          title="选择推送设备"
          is-link
          @click="showDevice=true"
          :value="isPullName"
          v-if="defaultValue"
      />
    </div>
    <!--      <van-cell v-if="isPullName == '全部设备'"/>-->
    <!--      部分设备UI-->
    <div v-if="isPullName == '部分设备' &&defaultValue " class="device">
      <div class="device-all">
        <div class="device-item" v-for="(item,index) in deviceBfList" :key="item.id">
          <div class="image-overlay" v-if="item.bindCount==3">
            <span class="overlay-text">已满4人</span>
          </div>
          <div class="circle-container">
            <div class="circle">
              <img :src="item.deviceImage?store.state.imgUrl+item.deviceImage:logo" alt="Circle Image"
                   class="circle-image">
            </div>
            <div class="selection-icon" @click="chooseDevice(item)">
              <img :src="item.isChecked==1 && item.bindCount!==3 ? select : unselect"
                   style="width: 12px;height: 12px;"/>
            </div>
          </div>
          <div style="font-size: 9px;font-weight: 400;margin-top: 10px;color: rgba(84, 84, 84, 1);text-align: center;">
            {{ item.deviceMode }}
          </div>
        </div>
      </div>
    </div>
    <div class="footer">
      <div class="size" @click="save">保存</div>
    </div>
    <!--    </div>-->

    <van-action-sheet v-model="showRelation" :actions="relationList" cancel-text="取消"
                      @select="onSelectRelation"/>
    <van-action-sheet v-model="showDevice" :actions="deviceList" cancel-text="取消"
                      @select="onSelectDevice"/>
  </div>
</template>

<script>
import {dateFormat} from "@/utils/date.js";
import {
  addByPhone, deleteFamilyFriend,
  deleteTester,
  getFriendList,
  getGenderList, getMasterDevice,
  getSmokingList,
  modifyUserBy,
  newTester
} from "../../../api/my";
import store from '../../../store'
import {Dialog} from 'vant';
import {mapState} from "vuex";

export default {
  name: "personInfo",
  data() {
    return {
      isDisabled: false,
      isSelected: false,
      store: store,
      title: '',
      back: require("@/assets/my/back.png"),
      unselect: require('@/assets/my/unselect.png'),
      select: require('@/assets/my/select.png'),
      relationList: [],
      deviceList: [
        {name: '部分设备', id: 0},
        {name: '全部设备', id: 1},
      ],
      showRelation: false,
      showDevice: false,
      logo: require("@/assets/tx.png"),
      defaultValue: false,
      isPullName: '',
      userInfo: {
        friendLabelTitle: '',
        friendLabel: '',//亲友关系 value
        friendName: '',//亲友姓名
        friendPhone: '',//亲友手机
        friendUserId: '',//亲友用户id
        id: '', //0 是新增 编辑的时候 拿列表id
        isPushAll: '',//1:全部 0:部分
        isPushData: '',//0:不推送 1:推送
        pushDevices: [],//部分设备时选中的设备
        avatar: ''
      },
      deviceBfList: [],
      result:''
    }
  },
  computed: {
    // ...mapState('my', ['phone', 'avatar', 'friendUserId'])

  },
  created() {
    // window["getInfoFromFlutter"] = (info) => {
    //   if (JSON.parse(info).action === 'upload') {
    //     // this.$toast(info)
    //     this.getInfoFromFlutter(info)
    //   }
    // };
  },
  async mounted() {
    window["getInfoFromFlutter"] = (info) => {//扫一扫功能
          if (JSON.parse(info).action === 'scanQR') {
              this.result = JSON.parse(info).param.result
              this.getInfoFromFlutter(info);
          }
    };
    if (this.$route.query.name) {
      this.$route.query.name === '新增' || '' ? this.title = '新增' : this.title = '编辑'
    } else {
      this.title = '新增'
    }
    if (this.$route.query.obj && this.$route.query.phoneParams) { //新增并完成手机号验证 满足该条件
      this.userInfo.friendLabel = this.$route.query.obj.friendLabel
      this.userInfo.friendName = this.$route.query.obj.friendName
      this.userInfo.pushDevices = []
      this.userInfo.isPushAll = this.$route.query.obj.isPushAll,//1:全部 0:部分
          this.userInfo.isPushData = this.$route.query.obj.isPushData,//0:不推送 1:推送
          // this.userInfo.friendLabel = this.$route.query.obj.friendLabel
      this.userInfo.friendPhone = this.$route.query.phoneParams.friendPhone
      this.userInfo.avatar = this.$route.query.phoneParams.avatar
      this.userInfo.friendUserId = this.$route.query.phoneParams.friendUserId
      console.log('add userinfo', this.userInfo)
    }

    if (this.title === '编辑') { //满足编辑的情况
      this.userInfo = this.$route.query.obj
      if (this.$route.query.relation) {
        this.userInfo.friendLabel = this.$route.query.relation
        // this.userInfo.friendLabel = this.$route.query.relation
      }
      console.log('edit userInfo', this.userInfo)
      this.isDisabled = true
      this.defaultValue = this.userInfo.isPushData === 0 ? false : true
      this.isPullName = this.userInfo.isPushAll === 0 ? '部分设备' : '全部设备'
      let data = {
        friendId: this.userInfo.id
      }
      this.deviceBfList = await this.getDevicesList(data)
      this.userInfo.pushDevices = this.deviceBfList.filter(item => item.isChecked == 1)
      console.log('编辑处理已选中', this.userInfo.pushDevices)
    } else {
      //新增 friendId 不传 编辑的时候 传好友id
      if (this.$route.query.relation) {
        // this.userInfo.friendLabelTitle = this.$route.query.relationIndex
        this.userInfo.friendLabel = this.$route.query.relation
      }
      let data = {
        friendId: ''
      }
      this.deviceBfList = await this.getDevicesList(data)
    }
    console.log('userInfo', this.userInfo)
    // this.personData.isDefault === 0 ? this.defaultValue = true : this.defaultValue = false //是否存在监护提醒
    //调用字典 获取关系
    let relations = await this.getRelation();//关系
    relations.forEach((item, index) => {
      let obj = {
        name: item.label,
        value: item.value
      }
      this.relationList.push(obj)
    })
  },
  watch: {
    'userInfo.defaultValue': {
      handler(newVal, oldVal) {
        console.log('222', newVal)
        this.defaultValue = !this.defaultValue
      }
    }
  },
  methods: {
    getParam(name) {
        if (this.result) {
                const query = this.result
                const vars = query.split("&");
                for (var i = 0; i < vars.length; i++) {
                var pair = vars[i].split("=");
                if (pair[0] == name) {
                    return pair[1];
                }
                }
            } else {
                return "";
        }

    },
     getInfoFromFlutter(info) {
          let data = JSON.parse(info);
          if (data.action == "scanQR" && data.param && data.param.result) {
              const url = this.getParam('url') ? this.getParam('url') : ''
              let data = {
                  name:this.getParam('name') ? this.getParam('name') : '',
                  phone:this.getParam('phone') ? this.getParam('phone') : '',
                  userId:this.getParam('userId') ? this.getParam('userId') : ''
              }
              if (url) {
                    this.$router.push({
                  // checkLoading
                      path: "/" + url,
                      query: data
                  })
              }
              
          }
        },
    // getInfoFromFlutter(info) {
    //   let data = JSON.parse(info);
    //   if (data.param.type == "image") {
    //     if (data.param.images && data.param.images.length > 0) {
    //       // this.imageList = data.param.images;
    //       this.userInfo.avatar = data.param.images[0]
    //     }
    //   }
    // },
    gotoRelation() {
      console.log('userInfo', this.userInfo)
      this.$router.push({path: '/addRelation', query: {obj: this.userInfo, name: this.title}})
    },
    gotoScanner() {
      // this.$toast('正在建设中')
       let message = {
                action: "scanQR",
                param: {
                  result: "checkLoading", //必填
                },
            };
        getInfoFromVue.postMessage(JSON.stringify(message));
    },
    chooseDevice(deviceItem) {
      deviceItem.isChecked == 0 ? deviceItem.isChecked = 1 : deviceItem.isChecked = 0
      const existingIndex = this.userInfo.pushDevices.findIndex(item => item.id === deviceItem.id);
      console.log("existingIndex", existingIndex)
      if (existingIndex !== -1) {
        this.userInfo.pushDevices.splice(existingIndex, 1);
      } else {
        this.userInfo.pushDevices.push(deviceItem);
      }
      console.log('999', this.userInfo.pushDevices)
    },
    getDevicesList(data) {
      return new Promise((resolve, reject) => {
        getMasterDevice(data).then(res => {
          resolve(res.data)
        })
      })

    },
    getRelation() {
      return new Promise((resolve, reject) => {
        getFriendList().then(res => {
          resolve(res.data)
        })
      })
    },
    onSelectRelation(item) {
      this.userInfo.friendLabel = item.value
      this.userInfo.friendLabelTitle = item.name
      this.showRelation = false
    },
    onSelectDevice(item) {
      this.userInfo.isPushAll = item.id
      this.isPullName = item.name
      this.showDevice = false
    },
    handleBack() {
      // this.$router.go(-1);
      this.$router.push({path: '/familyFriendList'})
    },
    changeImg() {
      let message = {
        action: "upload",
        param: {
          type: "image", //必填
          callback: 1,
        },
      };
      getInfoFromVue.postMessage(JSON.stringify(message));
    },
    del() {
      Dialog.confirm({
        title: '提示',
        message: '您确定要删除该亲友吗？',
        confirmButtonColor: 'rgba(242, 150, 0, 1)'
      }).then(() => {
        let data = {
          id: this.userInfo.id
        }
        deleteFamilyFriend(data).then(res => {
          if (res.success) {
            this.$toast.success('删除成功')
            this.$router.go(-1)
          }
        })
      }).catch(err => {

      })

    },
    save() {
      if (this.userInfo.id) {
        //编辑保存接口
        this.userInfo.isPushData = this.defaultValue ? 1 : 0
        addByPhone(this.userInfo).then(res => {
          if (res.success) {
            this.$toast.success('修改成功')
            this.$router.push({path: '/familyFriendList'})
          }
        })
      } else {
        //新增
        this.userInfo.isPushData = this.defaultValue ? 1 : 0
        addByPhone(this.userInfo).then(res => {
          if (res.success) {
            this.$toast.success('新增成功')
            this.$router.push({path: '/familyFriendList'})
          } else {
            this.$toast.fail(res.msg)
          }
        })
      }
    },
    handlePhone() {
      if (this.userInfo.phone && this.isDisabled) {
        this.$toast('不允许修改')
      } else {
        this.$router.push(
            {
              path: '/addFamilyFriendPhone',
              query: {obj: this.userInfo}
            }
        )
      }
    }
  }
}
</script>

<style scoped lang="less">
.main {
  //height: 100vh;
  //padding: 0px 15px;
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100vh;

  .header {
    height: 360px;

    .nav {
      height: 44px;
      display: flex;
      justify-content: center;
      align-items: center;

      .title {
        font-size: 20px;
        font-weight: 500;
      }

      .search {
        width: 20px;
        height: 20px;
        background-repeat: no-repeat;
        background-position: center;
        background-size: cover;
        background-image: url("../../../assets/friendScanner.png");
        position: absolute;
        right: 15px;
      }

      > img {
        width: 10px;
        height: 16px;
        position: absolute;
        left: 15px;
      }

      .del {
        position: absolute;
        right: 15px;
        font-size: 17px;
        font-weight: 400;
        line-height: 20.27px;
      }
    }

    .tx {
      display: flex;
      justify-content: center;
      padding-top: 14px;

      .avatar {
        background-repeat: no-repeat;
        background-size: 100%;
        width: 89px;
        height: 89px;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        background: rgba(0, 0, 0, 0.8);
        opacity: 1;
        background-repeat: no-repeat;
        background-position: center;
        background-size: cover;
        border: 1px solid #ebeef5;

        > img {
          width: 41px;
          height: 41px;
        }

      }

    }

    .change-avatar {
      font-size: 12px;
      font-weight: 400;
      letter-spacing: 0px;
      line-height: 17.38px;
      color: rgba(84, 84, 84, 1);
      text-align: center;
      margin-top: 5px;
    }

    //.header {
    //height: 200px;
    .field-with-switch {
      display: flex;
      align-items: center;
    }

    .field-with-switch .van-switch {
      //flex: 1;
      //margin-right: 10px;
      position: absolute;
      right: 25px;

    }

    .field-with-switch /deep/ .van-switch--on {
      background-color: rgba(242, 150, 0, 1);
    }
  }

  .device {
    flex: 1;
    overflow: auto;
    margin-top: 10px;
    //height: 200px;

    .device-all {
      display: flex;
      align-items: center;
      height: 75px;
      flex-wrap: wrap;
      justify-content: flex-start;

      .device-item {
        padding: 0px 20px;
        //border-right: 1px dashed #808080;
        width: calc((100% - 120px) / 3);
        text-align: center;
        margin-bottom: 15px;
        position: relative;

        .image-overlay {
          position: absolute;
          top: 1.2px;
          left: 14px;
          border-radius: 50%;
          width: 92px;
          height: 92px;
          background-color: rgba(0, 0, 0, 0.5);
          display: flex;
          justify-content: center;
          align-items: center;
          opacity: 0.8;
          z-index: 999;
        }

        .overlay-text {
          font-size: 16px;
          font-weight: 500;
          color: rgba(255, 255, 255, 1);
        }

        .avatar {
          width: 54.34px;
          height: 76.5px;
        }

        .circle-container {
          display: flex;
          flex-direction: column;
          align-items: center;
          position: relative;
        }

        .circle {
          width: 92px;
          height: 92px;
          border-radius: 50%;
          border: 1px solid rgba(128, 128, 128, 1);;
          //background-color: #ccc;
          display: flex;
          justify-content: center;
          align-items: center;
        }

        .circle-image {
          width: 54.34px;
          height: 76.5px;
          background-repeat: no-repeat;
          background-size: 100%;
        }

        .selection-icon {
          //margin-top: 10px;
          //text-align: center;
          position: absolute;
          bottom: -8px;
        }

        .selection-icon i {
          font-size: 24px;
          color: #ccc;
        }
      }
    }
  }

  .footer {
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 15px;
    margin-top: 10px;

    .size {
      width: 141px;
      height: 38px;
      //opacity: 1;
      border-radius: 19px;
      background: rgba(242, 150, 0, 1);
      font-size: 23px;
      font-weight: 500;
      //line-height: 38px;
      color: rgba(255, 255, 255, 1);
      //text-align: center;
      //vertical-align: top;
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 3px;
    }
  }

  /deep/ .van-cell {
    font-size: 17px;
  }

  /deep/ .van-action-sheet__name {
    font-size: 20px;
  }

  /deep/ .van-picker-column__item {
    font-size: 20px;
  }

  /deep/ .van-picker__confirm {
    font-size: 20px;
  }

  /deep/ .van-picker__cancel {
    font-size: 20px;
  }

  /deep/ .van-ellipsis {
    font-size: 20px;
  }


}
</style>
